/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.news;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.NewsModuleConstants;
import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.news.NewsManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.news.NewsItemForm;
import com.blandware.atleap.webapp.util.core.CacheUtil;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.MergeUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.news.NewsModuleWebConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>Updates news item
 * </p>
 * <p><a href="UpdateNewsItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.35 $ $Date: 2008/04/29 17:51:53 $
 * @struts.action path="/news/updateItem"
 * name="newsItemForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="news-item-update"
 * @struts.action-forward name="inputForward"
 * path=".news.updateItemAnnotation"
 * @struts.action-forward name="listNewsItems"
 * path="/news/listItems.do"
 * redirect="true"
 * @struts.action-forward name="callUpdateItem"
 * path=".news.updateItem"
 * @struts.action-forward name="callUpdateNewsItem"
 * path="/news/callUpdateItem.do"
 * redirect="false"
 */
public final class UpdateNewsItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        NewsItemForm newsItemForm = (NewsItemForm) form;
        String localesMode = newsItemForm.getLocalesMode();

		if ( isBackPressed(request) ) {
            // First check, may be session has been invalidated and we need to
            // fill content locales again
            if (request.getSession().getAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY) == null) {
                List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
                request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);
            }

            // check 'check all' ckeckbox if needed
            newsItemForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);

			return mapping.findForward("inputForward");
		}

		if ( isCancelled(request) ) {
            request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY);
            request.getSession().removeAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_BODY_KEY);
            if ( request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
                String redirectUrl = (String) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(redirectUrl, true);
            }
			return mapping.findForward("listNewsItems");
		}

		if ( request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY) == null ) {
			request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY, "update");

			Long newsItemId;
			if ( !GenericValidator.isBlankOrNull(newsItemForm.getId()) ) {
				newsItemId = Long.valueOf(newsItemForm.getId());
			} else {
				if ( log.isWarnEnabled() ) {
					log.warn("Missing news item ID. Returning to list...");
				}
				return mapping.findForward("listNewsItems");
			}

			request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_ID_KEY, newsItemId);

			NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);
			NewsItem newsItem = newsManager.retrieveNewsItem(newsItemId);

			if ( newsItem == null ) {
				// newsItem not found. it might be deleted by someone else
				ActionMessages errors = new ActionMessages();
				errors.add("newsItemNotFound", new ActionMessage("news.errors.notFound"));
				saveErrors(request, errors);
				return mapping.findForward("listNewsItems");
			}

			Map newAnnotation = new HashMap(newsItem.getAnnotation());
			Map newBody = new HashMap(newsItem.getBody());

			WebappUtil.copyProperties(newsItem, newsItemForm, request);

			Date publicationDate = newsItem.getPublicationDate();

			// set activity
			Date today = new Date();
			if ( publicationDate.compareTo(today) <= 0 ) {
				newsItem.setActive(Boolean.TRUE);
			} else {
				newsItem.setActive(Boolean.FALSE);
			}

            if (!"current".equalsIgnoreCase(localesMode) && !"all".equalsIgnoreCase(localesMode)) {
                localesMode = "selected";
            }

            Map annotationMap = newsItemForm.getAnnotationMap();
            Map bodyMap = newsItemForm.getBodyMap();
            Map annotationCheckedBoxes = newsItemForm.getAnnotationCheckedBoxes();
            Map bodyCheckedBoxes = newsItemForm.getBodyCheckedBoxes();
            if ("selected".equalsIgnoreCase(localesMode)) {
                for (Iterator i = annotationMap.entrySet().iterator(); i.hasNext();) {
                    Map.Entry entry = (Map.Entry) i.next();
                    String localeIdentifier = (String) entry.getKey();
                    if (annotationCheckedBoxes.get(localeIdentifier) == null) {
                        // if this locale is not checked, replace annotation with old one
                        annotationMap.put(localeIdentifier, newAnnotation.get(localeIdentifier));
                    }
                }
                for (Iterator i = bodyMap.entrySet().iterator(); i.hasNext();) {
                    Map.Entry entry = (Map.Entry) i.next();
                    String localeIdentifier = (String) entry.getKey();
                    if (bodyCheckedBoxes.get(localeIdentifier) == null) {
                        // if this locale is not checked, replace body with old one
                        bodyMap.put(localeIdentifier, newBody.get(localeIdentifier));
                    }
                }
            }

            WebappUtil.fillFieldValueWithDefaultLocaleValue(newsItemForm.getTitleMap(), newsItem.getTitle(), servlet.getServletContext());
            newsItem.setTitle(newsItemForm.getTitleMap());
            WebappUtil.copyFieldValue(newsItem.getAnnotation(), annotationMap);
            WebappUtil.copyFieldValue(newsItem.getBody(), bodyMap);
            
            String uri = NewsModuleWebConstants.NEWS_ITEM_URI_PREFIX + "/item" + newsItemForm.getId();
			newsItem.setUri(uri);

			// get all refs
			HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
			Set refs = new HashSet();
			for ( Iterator i = annotationMap.entrySet().iterator(); i.hasNext(); ) {
				Map.Entry entry = (Map.Entry) i.next();
				String locale = (String) entry.getKey();
				String annotation = (String) entry.getValue();
				String body = (String) bodyMap.get(locale);
                if (annotation != null) {
                    InputStream annotationIS = new ByteArrayInputStream(ConvertUtil.convertToByteArray(annotation));
                    refs.addAll(extractor.extractAllRefs(annotationIS, Constants.DEFAULT_ENCODING));
                }
                if ( !GenericValidator.isBlankOrNull(body) ) {
					InputStream bodyIS = new ByteArrayInputStream(ConvertUtil.convertToByteArray(body));
					refs.addAll(extractor.extractAllRefs(bodyIS, Constants.DEFAULT_ENCODING));
				}
			}

			Map linkedObjects = WebappUtil.mapObjectsToRefs(refs, request.getSession().getServletContext(), request.getContextPath());

			try {
                newsItem.setLastUpdatedDatetime(new Date());
                newsManager.updateNewsItem(newsItem, linkedObjects);

				// index news item
				SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
				searchManager.unIndexPage(newsItem.getUri(), request);
				if ( newsItem.getActive().booleanValue() ) {
					searchManager.indexPage(newsItem, request);
				}

				CacheUtil cacheUtil = CacheUtil.getInstance(request);
				cacheUtil.flushLocalizableFieldValueCache(newsItemId);

			} catch ( BeanAlreadyExistsException e ) {
				// newsItem already exists

                // check 'check all' ckeckbox if needed
                newsItemForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);

				ActionMessages errors = new ActionMessages();
				errors.add("newsItemAlreadyExists", new ActionMessage("errors.newsItemAlreadyExists", uri));
				saveErrors(request, errors);
				return mapping.getInputForward();
			} catch ( ObjectOptimisticLockingFailureException e ) {
				// news item was updated or deleted by another transaction
				ActionMessages errors = new ActionMessages();
				errors.add("updateFailed", new ActionMessage("news.errors.updateFailed"));
				saveErrors(request, errors);

				// merge annotation
                Map oldAnnotation = annotationMap;
				Map mergedAnnotation = new HashMap();
				for ( Iterator i = oldAnnotation.entrySet().iterator(); i.hasNext(); ) {
					Map.Entry entry = (Map.Entry) i.next();
					String locale = (String) entry.getKey();
					String oldValue = (String) entry.getValue();
					String newValue = (String) newAnnotation.get(locale);
					String mergedValue = MergeUtil.mergeHtml(oldValue, newValue);
					mergedAnnotation.put(locale, mergedValue);
				}
				request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_ANNOTATION_KEY, mergedAnnotation);

				// merge body
				Map oldBody = bodyMap;
				Map mergedBody = new HashMap();
				for ( Iterator i = oldBody.entrySet().iterator(); i.hasNext(); ) {
					Map.Entry entry = (Map.Entry) i.next();
					String locale = (String) entry.getKey();
					String oldValue = (String) entry.getValue();
					String newValue = (String) newBody.get(locale);
					String mergedValue = MergeUtil.mergeHtml(oldValue, newValue);
					mergedBody.put(locale, mergedValue);
				}
				request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_MERGED_BODY_KEY, mergedBody);

                // check 'check all' ckeckbox if needed
                newsItemForm.setAllCheckedFlagForAnnotationCheckboxes(request, localesMode);

				return mapping.findForward("callUpdateNewsItem");
			}
		}

		if ( request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
			String redirectUrl = (String) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
            return new ActionForward(redirectUrl, true);
		}

		return mapping.findForward("listNewsItems");
	}
}